package com.helu.lubike.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.helu.lubike.R;
import com.helu.lubike.databinding.ActivityBtSearchingBinding;
import com.helu.lubike.utils.Constants;
import com.helu.lubike.utils.SharedPreferencesUtils;
import com.helu.lubike.utils.Utils;
import com.helu.lubike.viewmodel.BTSearchingViewModel;

/**
 * @author helu  17-2-10 上午9:27
 * @description 蓝牙连续测据Activity
 */

public class BTSearchingActivity extends AppCompatActivity {

    private static final String MSG = "BTSearchingActivity";
    private ActivityBtSearchingBinding inflate;

    /**
     * 蓝牙模块的地址
     */
    private String btAddress;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice remoteDevice;
    private IntentFilter mFilter;

    private BTSearchingViewModel mViewModel;

    //BIKE_COMMAND
    //查詢
    private static final String CMD_CX = "$CX941010#";
    //預定
    private static final String  CMD_YD = "$YD941010#";
    //開鎖
    private static final String CMD_KS = "$KS941010#";
    //取消
    private static final String CMD_QX = "$QX941010#";
    //還車
    private static final String CMD_HC = "$HC941010#";

    //LED灯状态，黄灯=待使用，蓝灯=已预定 红灯=使用中
    private enum LEDS{LedYellow,LedBlue,LedRed}

    //车辆的状态
    private LEDS status;

    /**
     *
     */
    private boolean canCommunite;

    private BluetoothLeService mBluetoothLeService;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                Log.d(MSG, "device name: " + name);
                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                switch (state) {
                    case BluetoothDevice.BOND_NONE:
                        Log.d(MSG, "BOND_NONE 删除配对");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.d(MSG, "BOND_BONDING 正在配对");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        if (remoteDevice.getName().equals(device.getName())) {
                            Log.d(MSG, "BOND_BONDED 配对成功");
                            statTask();
                        }
                        break;
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflate = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_bt_searching, null, false);
        mViewModel = new BTSearchingViewModel();
        inflate.setViewModel(mViewModel);
        setContentView(inflate.getRoot());
        initView();
        initData();
        initListener();

    }

    private void initListener() {
        inflate.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    /**
     * 按钮被点击的事件
     * @param view
     */
    public void cmdBtnClick(View view){
        if (canCommunite) {
            handleViewClick(view);
        } else {
            if(mBluetoothLeService != null){
                mBluetoothLeService.connect(btAddress);
            }
            Utils.showToast(BTSearchingActivity.this, "设备通信故障,请稍后重试");
        }
    }

    private void initView() {
        mViewModel.initChart(inflate.lineChart);
    }

    private void initData() {
        btAddress = getIntent().getStringExtra("address");
        if (btAddress == null) {
            Utils.showToast(this, "找车失败");
            finish();
        }

        String bta = SharedPreferencesUtils.read(this, Constants.BTA, "59");
        String btn = SharedPreferencesUtils.read(this, Constants.BTN, "2");
        try {
            mViewModel.setBtParams(Float.valueOf(bta), Float.valueOf(btn));
        } catch (Exception e) {
            mViewModel.setBtParams(59.0f, 2.0f);
        }


        // 注册搜索完时的receiver
        mFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mReceiver, mFilter);


        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        remoteDevice = mBluetoothAdapter.getRemoteDevice(btAddress);
        if (remoteDevice != null) {
            inflate.title.setText("蓝牙定位(" + remoteDevice.getName() + ")");

            if (remoteDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                Log.d(MSG, "该设备已经完成配对");
                statTask();
            } else {
                remoteDevice.createBond();      //去配对
            }

        }

    }

    /**
     * 初始化完成,开始不断的测量Rssi 和 预约车辆
     */
    private void statTask() {
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        boolean isServiceConnected = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        Log.d(MSG, "Try to bindService=" + isServiceConnected);
    }



    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(MSG, "Unable to initialize Bluetooth");
                finish();
            }

            Log.e(MSG, "mBluetoothLeService is okay");

            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService.connect(btAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };


    // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    //                        or notification operations.
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {  //连接成功
                Log.e(MSG, "Only gatt, just wait");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { //断开连接
                canCommunite = false;

            }else if(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) //可以开始干活了
            {
                canCommunite = true;
                Log.e(MSG, "In what we need");
                mBluetoothLeService.WriteValue(CMD_CX);
                Log.e(MSG, "查询车辆状态命令已发出");

            }else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //收到数据
                Log.e(MSG, "RECV DATA");
                String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
                if (data != null) {
                    handleRCVData(data);
                }
            }else if(BluetoothLeService.ACTION_GATT_ONREADREMOTE_RSSI.equals(action)){ //received rssi value
                Log.e(MSG, "RECV RSSI DATA");
                int dataRssi = intent.getIntExtra(BluetoothLeService.EXTRA_DATA_RSSI,0);
                Log.d(MSG,"RSSI数据是:" + dataRssi);
                mViewModel.addRssi(dataRssi);
            }
        }
    };

    /**
     * 处理通过收到的数据
     * @param data
     */
    private void handleRCVData(String data) {
        Log.d(MSG,"handleRCVData:" + data);

        switch (data){
            case "CMD_ERR":
//                Utils.showToast(this,"命令格式错误");
                break;
            case "PWD_ERR":
                Utils.showToast(this,"密码错误");
                break;

            case "B_FREE":
                status=LEDS.LedYellow;
                inflate.bikeStaus.setText("空闲中");
                changeIcon(inflate.bikeStaus,R.mipmap.light_green);
                inflate.cmd2Container.setVisibility(View.VISIBLE);
                inflate.cmd1.setVisibility(View.GONE);
                inflate.cmd2Container1.setText("开锁");
                inflate.cmd2Container2.setText("预定");
                break;

            case "B_RSVD":
                status=LEDS.LedBlue;
                inflate.bikeStaus.setText("已预定");
                changeIcon(inflate.bikeStaus,R.mipmap.light_blue);
                inflate.cmd2Container.setVisibility(View.VISIBLE);
                inflate.cmd1.setVisibility(View.GONE);
                inflate.cmd2Container1.setText("取消");
                inflate.cmd2Container2.setText("开锁");
                break;

            case "B_USING":
                status=LEDS.LedRed;
                inflate.bikeStaus.setText("使用中");
                changeIcon(inflate.bikeStaus,R.mipmap.light_red);
                inflate.cmd2Container.setVisibility(View.GONE);
                inflate.cmd1.setVisibility(View.VISIBLE);
                inflate.cmd1.setText("还车");
                break;


            case "E_FREE":
                Utils.showToast(this,"车辆已处于空闲中");
                break;
            case "E_RSVD":
                Utils.showToast(this,"车辆已被预定");
                break;
            case "E_USING":
                Utils.showToast(this,"车辆使用中");
                break;

            case "O_FREE":
                status=LEDS.LedYellow;
                inflate.bikeStaus.setText("空闲中");
                changeIcon(inflate.bikeStaus,R.mipmap.light_green);
                inflate.cmd2Container.setVisibility(View.VISIBLE);
                inflate.cmd1.setVisibility(View.GONE);
                inflate.cmd2Container1.setText("开锁");
                inflate.cmd2Container2.setText("预定");
                break;

            case "O_RSVD":
                status=LEDS.LedBlue;
                inflate.bikeStaus.setText("已预定");
                changeIcon(inflate.bikeStaus,R.mipmap.light_blue);
                inflate.cmd2Container.setVisibility(View.VISIBLE);
                inflate.cmd1.setVisibility(View.GONE);
                inflate.cmd2Container1.setText("取消");
                inflate.cmd2Container2.setText("开锁");
                break;

            case "O_USING":
                status=LEDS.LedRed;
                inflate.bikeStaus.setText("使用中");
                changeIcon(inflate.bikeStaus,R.mipmap.light_red);
                inflate.cmd2Container.setVisibility(View.GONE);
                inflate.cmd1.setVisibility(View.VISIBLE);
                inflate.cmd1.setText("还车");
                break;

            default:
                Utils.showToast(this,"操作失败,请稍后重试");
                break;
        }
    }

    /**
     * 改变好状态按钮的显示图标
     * @param view
     * @param drawableId
     */
    private void changeIcon(TextView view,int drawableId){
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        view.setCompoundDrawables(null, drawable,null,null);
    }

    /**
     * 按钮被点击了
     * @param view
     */
    private void handleViewClick(View view) {
        String cmdChar = ((TextView) view).getText().toString();
        switch (cmdChar){
            case "开锁":
                mBluetoothLeService.WriteValue(CMD_KS);
                break;
            case "预定":
                mBluetoothLeService.WriteValue(CMD_YD);
                break;
            case "取消":
                mBluetoothLeService.WriteValue(CMD_QX);
                break;
            case "还车":
                mBluetoothLeService.WriteValue(CMD_HC);
                break;

        }
    }


    private static IntentFilter makeGattUpdateIntentFilter() {                        //注册接收的事件
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothDevice.ACTION_UUID);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_ONREADREMOTE_RSSI);
        return intentFilter;
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
        unbindService(mServiceConnection);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mBluetoothLeService != null){
            mBluetoothLeService.close();
            mBluetoothLeService = null;
        }

        //解除注册
        unregisterReceiver(mReceiver);
        mViewModel.destroy();
    }
}
